package cn.ibobo.lease.app.service.impl;

import cn.ibobo.lease.app.dao.*;
import cn.ibobo.lease.app.service.UserCouponService;
import cn.ibobo.lease.app.service.UserOrderService;
import cn.ibobo.lease.app.service.UserPointService;
import cn.ibobo.lease.common.base.BaseMapper;
import cn.ibobo.lease.common.base.BaseServiceImpl;
import cn.ibobo.lease.common.dto.*;
import cn.ibobo.lease.common.enums.ResultEnum;
import cn.ibobo.lease.common.util.DateUtil;
import cn.ibobo.lease.common.util.UuidUtil;
import com.alibaba.fastjson.JSONArray;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.List;


/**
 * 用户订单表业务处理接口
 * @Author lililiang
 * @Date 2018-12-22 14:49:46
 */
@Service
public class UserOrderServiceImpl extends BaseServiceImpl<UserOrderDTO, String> implements UserOrderService {

    private static final Log LOGGER = LogFactory.getLog(UserOrderServiceImpl.class);

    @Autowired
    private UserOrderMapper mapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private UserOrderDetailMapper userOrderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private UserPointService userPointService;

    @Override
    protected BaseMapper<UserOrderDTO, String> getMapper() {
        return mapper;
    }

    /**
     * 用户订单表列表
     * @Author lililiang
     * @Date 2018-12-22 14:49:46
     * @Param
     * @Return
     */
    @Override
    public List<UserOrderDTO> list4Page(UserOrderDTO entity, Integer pageNum, Integer... pageSize) {
        return super.list4Page(entity, pageNum, pageSize);
    }

    /**
     * 用户订单表列表（无分页）
     * @Author lililiang
     * @Date 2018-12-22 14:49:46
     * @Param
     * @Return
     */
    @Override
    public List<UserOrderDTO> listByCondition(UserOrderDTO entity) {
        return super.listByCondition(entity);
    }

    /**
     * 查询用户订单表详情信息
     * @Author lililiang
     * @Date 2018-12-22 14:49:46
     * @Param
     * @Return
     */
    @Override
    public UserOrderDTO queryOneByPk(String id) {
        return super.queryOneByPk(id);
    }

    /**
     * 保存用户订单表信息
     * @Author lililiang
     * @Date 2018-12-22 14:49:46
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer save(UserOrderDTO entity) {
        String id = entity.getId();
        if(id == null){
            //新增订单
            //1. 校验点金券，并核销使用状态
            String ucid = entity.getUcid();
            if(ucid != null){
                BigDecimal couponmoney = entity.getCouponmoney();
                UserCouponDTO userCouponDTO = userCouponMapper.queryOneByPk(ucid);
                if(userCouponDTO == null){
                    //无此点金券
                    return ResultEnum.NO_COUP.getCode();
                }else if(userCouponDTO.getStatus() != 0){
                    //此点金券已使用或已失效
                    return ResultEnum.COUP_LOSE_EFF.getCode();
                }else if(couponmoney.compareTo(userCouponDTO.getMoney()) != 0){
                    //点金券和优惠金额不匹配
                    return ResultEnum.COUP_NO_MATCH.getCode();
                }
                userCouponDTO = new UserCouponDTO();
                userCouponDTO.setId(ucid);
                userCouponDTO.setStatus(1);
                if(userCouponMapper.edit(userCouponDTO) <= 0){
                    return ResultEnum.FAIL.getCode();
                }
            }
            //2. 保存订单主表
            entity.setId(UuidUtil.getUuid());
            entity.setCreatetm(DateUtil.getNow());
            if(mapper.add(entity) <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultEnum.FAIL.getCode();
            }
            //3. 转换封装，并保存订单子表
            String childrenJson = entity.getChildrenJson();
            if(childrenJson != null && childrenJson.length() > 0){
                List<UserOrderDetailDTO> userOrderDetailDTOS = JSONArray.parseArray(childrenJson, UserOrderDetailDTO.class);
                if(userOrderDetailDTOS != null && userOrderDetailDTOS.size() > 0){
                    for(UserOrderDetailDTO tempDTO : userOrderDetailDTOS){
                        tempDTO.setId(UuidUtil.getUuid());
                        tempDTO.setOid(entity.getId());
                        tempDTO.setCreatetm(DateUtil.getNow());
                    }
                    userOrderDetailMapper.addBatch(userOrderDetailDTOS);
                }
            }
            return ResultEnum.SUCCESS.getCode();
        }else{
            //修改订单，这里的业务需要根据实际业务处理
            return ResultEnum.NO_SUPPORT_EDIT.getCode();
        }
    }

    /**
     * 删除用户订单表信息
     * @Author lililiang
     * @Date 2018-12-22 14:49:46
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer delete(String id) {
        return super.delete(id);
    }

    /**
     * @Description 购买线上商品
     * @Author lililiang
     * @Date 2019/2/17 14:28
     * @Param [entityDTO]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer buy(UserOrderDTO entityDTO){
        //1. 校验用户等级是否可购买商品
        UserDTO userDTO = userMapper.queryOneByPk(entityDTO.getUid());
        if(userDTO == null || userDTO.getLevel() == null){
            return ResultEnum.FAIL.getCode();
        }
        GoodsDTO goodsDTO = goodsMapper.queryOneByPk(entityDTO.getGid());
        if(goodsDTO == null){
            return ResultEnum.FAIL.getCode();
        }
        if(userDTO.getLevel() < goodsDTO.getUselevel()){
            return  ResultEnum.LEVEL_TOO_LOW.getCode();
        }
        //2. 生成订单信息
        entityDTO.setId(UuidUtil.getUuid());
        entityDTO.setCreatetm(DateUtil.getNow());
        entityDTO.setAddress(userDTO.getAddress());
        if(mapper.add(entityDTO) <= 0){
            return ResultEnum.FAIL.getCode();
        }
        //3. 修改会员充值金总额
        userDTO.setBalance(entityDTO.getUsemoney());
        userDTO.setType((byte)2); //减少充值金
        if(userMapper.balance(userDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.NO_ENOUGH_BALANCE.getCode();
        }
        //4. 根据消费返还点金券比例计算返还的点金券金额
        DictDTO dict = new DictDTO();
        dict.setMasterCode("coupon_ratio");
        List<DictDTO> dictDTOS = dictMapper.listByCondition(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //5. 生成点金券赠送记录   修改会员点金总额
        UserCouponDTO couponDTO = new UserCouponDTO();
        couponDTO.setUid(entityDTO.getUid());
        couponDTO.setMoney(entityDTO.getUsemoney()
                .multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString()))
                .multiply(new BigDecimal("0.01")));//查询的比例为百分比，需要乘0.01
        couponDTO.setType(4); //1平台发放，2充值赠送，3租赁赠送，4线上购物赠送，5线下购物赠送 6线下购物使用
        couponDTO.setBusId(entityDTO.getId());
        if(userCouponService.coupon(couponDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //6. 根据消费返还积分比例计算返还的积分数量
        dict.setMasterCode("point_ratio");
        dictDTOS = dictMapper.listByCondition(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //7. 生成积分赠送记录 / 修改会员当前积分/总积分
        UserPointDTO pointDTO = new UserPointDTO();
        pointDTO.setUid(entityDTO.getUid());
        pointDTO.setPoint(entityDTO.getUsemoney()
                .multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString())
                .multiply(new BigDecimal("0.01")))
                .intValue());
        pointDTO.setType((byte)4);//1 使用积分  2 充值赠送  3 租赁赠送  4线上购物赠送
        pointDTO.setBusId(entityDTO.getId());
        if (userPointService.point(pointDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        return ResultEnum.SUCCESS.getCode();

    }
}
